<template>
  <div id="select-extend-att">
    <Form :model="form" ref="templateListForm" :rules="rules">
      <Form-item prop="attributeTemplateId">
        <Select v-model="form.attributeTemplateId">
          <Option v-for="item in templateList" :key="item.id" :value="item.id">{{ item.templateName }}</Option>
        </Select>
      </Form-item>
    </Form>
  </div>
</template>

<script>
export default {
  name: 'select-extend-att',
  props: {
    requestMethod: {
      type: String,
      default: 'get'
    },
    requestPath: {
      type: String,
      default: '',
      required: true
    },
    requestParams: {
      type: Object,
      default: () => ({}),
      required: true
    }
  },
  data() {
    return {
      form: {
        attributeTemplateId: ''
      },
      rules: {
        attributeTemplateId: [{ trigger: 'change', required: false, message: '请选择拓展属性模板' }]
      },
      templateList: [],
      actions: [
        {
          text: '关闭',
          theme: 'default',
          handle: () => {
            this.$emit('Close')
          }
        },
        {
          text: '确认',
          theme: 'primary',
          handle: () => {
            this.onOk()
          }
        }
      ]
    }
  },
  created() {
    this.initData()
    this.$emit('SetTitle', '选择拓展属性模板')
    this.$emit('SetPageWidth', 350)
    this.$emit('SetPageActions', this.actions)
  },
  methods: {
    initData() {
      const { requestMethod, requestPath, requestParams } = this
      const reqMethod = requestMethod.toLowerCase()
      $http[reqMethod](requestPath, requestParams)
        .then(res => {
          this.templateList = res.data
        })
        .catch(err => console.error(err))
    },
    onOk() {
      this.actions[1].loading = true
      this.$refs['templateListForm'].validate(valid => {
        if (valid) {
          this.actions[1].loading = false
          // attributeId、attributeTemplateId都是拓展属性模板ID，后端开发字段名未统一，所以写两个……
          this.$emit('Close', {
            attributeId: this?.form?.attributeTemplateId || '',
            attributeTemplateId: this?.form?.attributeTemplateId || ''
          })
        } else {
          this.actions[1].loading = false
        }
      })
    }
  }
}
</script>
